package com.example.easyexceldemo.demos.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.example.easyexceldemo.demos.mapper.StudentMapper;
import com.example.easyexceldemo.demos.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author 杨光 微信号:tolryg
 * @time 10:39
 */
@Service
public class StudentService {

    @Autowired
    private StudentMapper studentMapper;

    public void download(HttpServletResponse response) {

        String title="学生信息列表";
        List<Student> studentList = studentMapper.selectAll();

        //设置响应的媒体类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //设置响应字符集
        response.setCharacterEncoding("utf-8");

        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = null;
        try {
            fileName = URLEncoder.encode(title, "UTF-8").replaceAll("\\+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        // 这里需要设置不关闭流
        try {

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), Student.class)
                    .autoCloseStream(Boolean.FALSE).build();

            WriteSheet sheet1 = EasyExcel.writerSheet(1, "学生信息1").build();
            excelWriter.write(studentList, sheet1);
            WriteSheet sheet2 = EasyExcel.writerSheet(2, "学生信息2").build();
            excelWriter.write(studentList, sheet2);

//                    .sheet("学生信息1")
//                    .doWrite(studentList);

            excelWriter.finish();
        } catch (IOException e) {
                e.printStackTrace();
        }
    }

    public void upload(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), Student.class, new StudentExcelReadListener(this.studentMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("上传报错");
        }

    }
}
